﻿using Naruto.FileStorage.Abstractions;
using Naruto.FileStorage.Helper;
using Naruto.FileStorage.Provider.MongoDB.Interface;
using Naruto.FileStorage.Provider.MongoDB.Object;
using Naruto.MongoDB.Interface;
using System;
using System.IO;
using System.Threading.Tasks;

namespace Naruto.FileStorage.Provider.MongoDB
{
    /// <summary>
    /// mongodb文件操作
    /// </summary>
    public sealed class MongoDBFileStorage : IFileStorage
    {
        private readonly IMongoDBFile mongoDBFile;

        public MongoDBFileStorage(IMongoDBFile _mongoDBFile)
        {
            mongoDBFile = _mongoDBFile;
        }

        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="fileStream"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public async Task<string> AddFileAsync(Stream fileStream, string fileName)
        {
            //判断当前是否为大的文件类型
            if (fileStream == null || !fileStream.CanRead || fileStream.Length <= 0)
            {
                return default;
            }
            var isBig = fileStream.Length > MongoDBFileStorageConst.MaxFileLengthLimit;
            //先删除
            var fileNameSplit = fileName.SplitFileName();
            if (fileNameSplit == null)
            {
                return default;
            }
            await mongoDBFile.DeleteFileAsync(isBig, fileNameSplit);
            return await mongoDBFile.AddFileAsync(fileStream, isBig, fileNameSplit);
        }

        public async Task DeleteFileAsync(string fileName)
        {
            var fileNameSplit = fileName.MongoDBFileNameSplit();
            if (fileNameSplit.fileNameSplit == null)
            {
                return;
            }
            await mongoDBFile.DeleteFileAsync(fileNameSplit.isBig, fileNameSplit.fileNameSplit);
        }

        public async Task<byte[]> GetFileAsync(string fileName)
        {
            var fileNameSplit = fileName.MongoDBFileNameSplit();
            if (fileNameSplit.fileNameSplit == null)
            {
                return default;
            }
            return await mongoDBFile.GetFileAsync(fileNameSplit.isBig, fileNameSplit.fileNameSplit);
        }
    }
}
